<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        html,
        body {
            width: 100%;
            height: 100%;
        }

        .box {
            background-color: skyblue;
            width: 200px;
            height: 200px;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <script>
        let box = document.querySelector('.box')

        box.onmousedown = () => {
            document.onmousemove = (e) => {
                let x = e.clientX - box.offsetWidth/2
                let y = e.clientY - box.offsetHeight/2
                x = x>0 ? x : 0
                y = y>0 ? y : 0

                x = x >=document.documentElement.clientWidth-box.clientWidth?document.documentElement.clientWidth-box.clientWidth:x
                y = y >=document.documentElement.clientHeight-box.clientHeight?document.documentElement.clientHeight-box.clientHeight:y

                box.style.marginLeft = x + 'px'
                box.style.marginTop = y + 'px'
            }
        }

        box.onmouseup = ()=>{
            document.onmousemove = null
        }
    </script>
</body>

</html>